<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : File.php
 * Created on : 2021-2-2 14:18:51
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\api\controller;

use think\App;
use app\Request;
use think\exception\ValidateException;
use think\Filesystem;
use haoteam\service\UtilService;

/**
 * 文件管理
 * Class File
 * Tiger <1192851302@qq.com> 2021-2-2 14:18:51
 */
class File {

    /**
     * 上传图片
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @param type $mid
     * @return type
     */
    public function upload_image(Request $request, App $app) {
        [$store_path] = UtilService::postMore([
                    ['path', $request->appName()]
                        ], $request, true);
        $file = request()->file('image');
        $Filesystem = new Filesystem($app);
        try {
            validate(['image' => ['fileSize' => (1024 * 1024) * 2, 'fileExt' => 'jpg,png,jpeg']])->check(['image' => $file]);
            $path = $Filesystem->disk('public')->putFile($store_path, $file);
            // 拼接URL路径
            $url = request()->domain() . $Filesystem->getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path);
        } catch (ValidateException $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful([
                    'url' => $url
        ]);
    }

    /**
     * 上传文件
     * @login true
     * @author Tiger <1192851302@qq.com>
     * @param Request $request
     * @return type
     */
    public function upload_file(Request $request, App $app) {
        [$store_path] = UtilService::postMore([
                    ['path', $request->appName()]
                        ], $request, true);
        $file = request()->file('file');
        $Filesystem = new Filesystem($app);
        try {
            validate(['file' => ['fileSize' => (1024 * 1024) * 20, 'fileExt' => 'mp3,mp4']])->check(['file' => $file]);
            $path = $Filesystem->disk('public')->putFile($store_path, $file);
            // 拼接URL路径
            $url = request()->domain() . $Filesystem->getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path);
        } catch (ValidateException $exc) {
            return app('json')->fail($exc->getMessage());
        }
        return app('json')->successful([
                    'url' => $url
        ]);
    }

}
